<template>
  <ion-app>
    <ion-page>
    </ion-page>
  </ion-app>
</template>
<script setup lang="ts">
import { IonPage,IonApp } from '@ionic/vue';
import {   onMounted, onUnmounted,ref } from 'vue';
import { LocalNotifications } from '@capacitor/local-notifications';
import { App, AppState } from '@capacitor/app';
// import { BackgroundRunner } from '@capacitor/background-runner';
import service from '@/api/api';

const oldmessage = ref(localStorage.getItem('lastAlertId') || '');
const infos=ref('')
const alertData=ref('')
let num=0 

const fetchData =async () => {
      try {       
        const response=await service.post('/alertApi/getAlerts',{length:'10'})
        infos.value= response.data.data.list[0];
        alertData.value =  String(response.data.data.list[0].alertId);
        localStorage.setItem('lastAlertId', alertData.value);
          console.log(response.data);
          if(alertData.value!==oldmessage.value){
            num++
            await LocalNotifications.schedule({
              notifications: [{
                title:'new message',
                body:infos.value,
                id: num, 
                schedule: { at: new Date(Date.now()+1000*0.5) },
                group: 'alert_group',
                groupSummary: true,
                threadIdentifier: 'alert_thread' 
              }]
            });
          }
          oldmessage.value=alertData.value
      } catch (error) {
        // 处理请求错误
        console.error('Error fetching data:',error);
      }
    }    
    onMounted(fetchData);
let intervalId: ReturnType<typeof setInterval>;
onMounted(() => {
  intervalId = setInterval(async () => {
    fetchData()
  }, 1000*60);
 });
  // 清理轮询
  onUnmounted(() => {
    clearInterval(intervalId);
  });
// const scheduleNotification = async () => {
//   num++;
//   await LocalNotifications.schedule({
//         notifications: [{
//           title:'new meg',
//           body:alertData.value,
//           id:num, 
//           schedule: { at: new Date(Date.now()+1000*1) }, 
//         }]
//       });
//     } 



const handleAppStateChange = async (state: AppState) => {
    if (!state.isActive) {
        // 应用进入后台，启动后台任务
    const { BackgroundRunner } = await import('@capacitor/background-runner');
    await BackgroundRunner.dispatchEvent({
      event: 'background-alert',
      label: '',
      details: {}
    });
  }
};

onMounted(() => {
    // 挂载时添加应用状态变化监听器
    App.addListener('appStateChange', handleAppStateChange);
});

onUnmounted(() => {
    // 卸载时移除所有监听器
    App.removeAllListeners();
});
</script>
 

